package com.asset.dispoal.commom.permission;

import com.alibaba.fastjson2.JSONException;
import com.alibaba.fastjson2.JSONObject;
import com.asset.dispoal.commom.permission.dto.PermissionDTO;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import tech.mhuang.pacebox.core.exception.BusinessException;
import tech.mhuang.pacebox.springboot.core.entity.RequestModel;
import tech.mhuang.pacebox.springboot.core.local.GlobalHeaderThreadLocal;
import tech.mhuang.pacebox.springboot.core.permission.annotation.Permission;
import tech.mhuang.pacebox.springboot.core.permission.extra.IPermissionManager;
import tech.mhuang.pacebox.springboot.core.rest.SingleRestTemplate;
import tech.mhuang.pacebox.springboot.core.spring.start.SpringContextHolder;
import tech.mhuang.pacebox.springboot.protocol.GlobalHeader;

/**
 * 权限验证服务
 *
 * @author mhuang
 * @since 1.0.0
 */
@Component("permissionManager")
public class DefaultPermissionUserManager implements IPermissionManager {

    @Override
    public void permission(Permission permissionUser) {
        GlobalHeader global = GlobalHeaderThreadLocal.getOrException();
        PermissionDTO permissionDO = new PermissionDTO();
        permissionDO.setUserId(global.getUserId());
        permissionDO.setAuthCode(permissionUser.code());
        permissionDO.setCarry(permissionUser.param());
        SingleRestTemplate singleRestTemplate = SpringContextHolder.getBean(SingleRestTemplate.class);
        Environment environment = SpringContextHolder.getApplicationContext().getEnvironment();
        RequestModel<String> requestModel = new RequestModel<String>() {
        };
        requestModel.setParams(permissionDO);
        requestModel.setMethod(HttpMethod.GET);
        requestModel.setUrl(environment.getProperty("permission.url"));
        requestModel.setSufUrl("extension/permission/check");
        ResponseEntity<String> response = singleRestTemplate.request(requestModel);
        if (response.getBody() != null) {
            try {
                if (JSONObject.parseObject(response.getBody()).getInteger("code") == 0) {
                    throw new BusinessException(500, "当前用户无权限访问");
                }
            } catch (JSONException ignored) {

            }
        }
        global.getExtraMap().put("permission", response.getBody());
    }
}